import { BrowserWindow, globalShortcut, ipcMain, Menu } from 'electron'

/**
 * 配置菜单允许开发者工具
 */
export function setupMenus(): void {
  const menu = Menu.buildFromTemplate([
    {
      label: '开发者',
      submenu: [
        {
          label: '切换开发者工具',
          accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
          click: (_, window): void => {
            if (window instanceof BrowserWindow) {
              if (window.webContents.isDevToolsOpened()) {
                window.webContents.closeDevTools()
              } else {
                window.webContents.openDevTools({ mode: 'right' })
              }
            }
          },
        },
        { type: 'separator' },
        { role: 'reload' },
      ],
    },
  ])
  Menu.setApplicationMenu(menu)
}

/**
 * 设置快捷键
 * @param win
 * @note 尚未生效
 */
export function setupShortcut(win: BrowserWindow): void {
  function registerShortcuts(): void {
    if (!globalShortcut.isRegistered('F6')) {
      globalShortcut.register('F6', () => {
        if (win.webContents.isDevToolsOpened()) {
          win.webContents.closeDevTools()
        } else {
          win.webContents.openDevTools({ mode: 'right' })
        }
      })
    }
  }

  win.on('focus', registerShortcuts)
  win.on('blur', () => globalShortcut.unregisterAll())
}

ipcMain.on('toggle-devtools', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender)
  if (win.webContents.isDevToolsOpened()) {
    win.webContents.closeDevTools()
  } else {
    win.webContents.openDevTools({ mode: 'right' })
  }
})
